
package com.skcc.cop.mrtaxi.biz;


import java.util.ArrayList;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.projectteam.http.util.DeviceUtil;
import com.skcc.cop.mrtaxi.BaseActivity;
import com.skcc.cop.mrtaxi.R;
import com.skcc.cop.mrtaxi.R.color;
import com.skcc.cop.mrtaxi.biz.destination.DestinationEntity;
import com.skcc.cop.mrtaxi.http.CallListener;
import com.skcc.cop.mrtaxi.util.Dialogs;
import com.skcc.cop.mrtaxi.util.Dialogs.DialogListener;
import com.skcc.cop.mrtaxi.util.LogControl;
import com.skcc.cop.mrtaxi.util.Variables;
import com.skcc.cop.mrtaxi.view.TitleBar;
import com.skcc.cop.mrtaxi.view.TitleBar.OnTitleBarEventListener;


public class CallRequestActivity extends BaseActivity implements OnTitleBarEventListener{

	// ===========================================================
	// Constants
	// ===========================================================
	private static final String TAG = CallRequestActivity.class.getSimpleName();
	private ArrayList<DestinationEntity> destinationEntity;
	private ArrayList<String> list = new ArrayList<String>();
	
	
	// ===========================================================
	// Fields
	// ===========================================================
	public static boolean isForeground = false;
	private TitleBar mTitleBarView;
	private Button callRequestButton;
	private Button callCancelButton;
	private Button callSuccessButton;
	private Spinner destinationSpinner;
	private String driverPhoneNumber;
	private double userLatitude;
	private double userLongitude;
	private int distance;
	
	private Handler handler = new Handler();
	private int updatedTime = 30; // 300초 == 5분
	private boolean pushed = false;
	
	private String message;
	private int TimeOverCD = 0;

	// ===========================================================
	// Methods for/from SuperClass/Interfaces
	// ===========================================================
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_call_request);
		
		mTitleBarView = (TitleBar) this.findViewById(R.id.titlebar_view);
		mTitleBarView.setEventListener(this);
		mTitleBarView.showBack();
		mTitleBarView.setTitle(R.string.title);
		
		ImageView imgUrlImageview = (ImageView) this.findViewById(R.id.driver_imageurl_imageview);
		// TextView driverNameTextview = (TextView) this.findViewById(R.id.driver_name_textview);
		TextView carNumberTextview = (TextView) this.findViewById(R.id.driver_carnumber_textview);
		// TextView companyNameTextview = (TextView) this.findViewById(R.id.driver_companyname_textview);
		TextView driverNameCompanyTextview = (TextView) this.findViewById(R.id.driver_name_company_textview);
		destinationSpinner = (Spinner) this.findViewById(R.id.destination_spinner);
		callRequestButton = (Button) this.findViewById(R.id.call_request_button);
		callCancelButton = (Button) this.findViewById(R.id.call_cancel_button);
		callSuccessButton = (Button) this.findViewById(R.id.call_success_button);
		callRequestButton.setOnClickListener(clickListener);
		callCancelButton.setOnClickListener(clickListener);
		// callSuccessButton.setOnClickListener(clickListener)
		callSuccessButton.setVisibility(View.GONE);
		callSuccessButton.setClickable(false);
		callRequestButton.setText("요청");
		
		Bundle bundle = this.getIntent().getBundleExtra("driver");
		String driverName;
		String carNumber;
		String companyName;
		String imgUrl;
		if (bundle != null) {
			driverName = bundle.getString("driverName");
			carNumber = bundle.getString("carNumber");
			companyName = bundle.getString("companyName");
			imgUrl = bundle.getString("imgUrl");
			driverPhoneNumber = bundle.getString("driverPhoneNumber");
			userLatitude = bundle.getDouble("userLatitude");
			userLongitude = bundle.getDouble("userLongitude");
			distance = bundle.getInt("distance");
		} else {
			SharedPreferences driverSharedPref = getSharedPreferences("driverSharedPref", MODE_PRIVATE);
			driverName = driverSharedPref.getString("driverName", "N/A");
			carNumber = driverSharedPref.getString("carNumber", "N/A");
			companyName = driverSharedPref.getString("companyName", "N/A");
			imgUrl = driverSharedPref.getString("imgUrl", "N/A");
			driverPhoneNumber = driverSharedPref.getString("driverPhoneNumber", "N/A");
			userLatitude = driverSharedPref.getFloat("userLatitude", (float) 0);
			userLongitude = driverSharedPref.getFloat("userLongitude", (float) 0);
			distance = driverSharedPref.getInt("distance",0);
			callRequestButton.setVisibility(View.GONE);
			callCancelButton.setVisibility(View.GONE);
			//callSuccessButton.setVisibility(View.VISIBLE);
		}
		
		if ("".equals(imgUrl)) {
			imgUrlImageview.setBackgroundResource(R.drawable.not_registered);
		} else {
			application.getImageLoader().displayImage(imgUrl, imgUrlImageview);
		}
		
		application.getImageLoader().displayImage(imgUrl, imgUrlImageview);
		// driverNameTextview.setText("기사 이름 : " + driverName);
		carNumberTextview.setText("차량 번호 : " + carNumber);
		// companyNameTextview.setText("회사명 : " + companyName);
		destinationEntity = dataBaseControl.getDestinationListAll();
		driverNameCompanyTextview.setText(driverName + "( " + companyName + ")");
		int i = 0;
		for (DestinationEntity entity : destinationEntity) {
			Log.i(TAG, "entity.getId() = " + entity.getId());
			list.add(entity.getAddress1() + " : " + entity.getPassenger() + "명");
			i++;
		}
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list) {
			// public View getView(int position, View convertView, ViewGroup parent) {
			// View v = super.getView(position, convertView, parent);
			// ((TextView)v).setTextSize(16);
			// ret
			// }
			//
			// public View getDropDownView(int position, View convertView, ViewGroup parent) {
			// View v = super.getDropDownView(position, convertView, parent);
			// ((TextView)v).setGravity(Gravity.CENTER);
			// return v;
			// }
		};
		dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		destinationSpinner.setAdapter(dataAdapter);
	}

	@Override
	protected void onResume() {
		super.onResume();
		LogControl.d(TAG, " in CallRequestActivity onResume >>>>>");
		isForeground = true;
	}

	@Override
	protected void onPause() {
		super.onPause();
		LogControl.d(TAG, " in CallRequestActivity onPause >>>>>");
		isForeground = false;
	}
	
	// TODO : noti 를 클릭하면 여기 메소드가 호출된다.
	// 여기서 콜 요청 버튼의 이름을 요청 승낙 완료 상태로 변경한다.
	@Override
	protected void onNewIntent(Intent intent) {
		
		String message = intent.getStringExtra(Variables.CALL_REQUEST_SUCCESS_MESSAGE);
		
		if (message != null && !"".equals(message)) {
			callRequestButton.setText("기사 응답 완료");
			callRequestButton.setEnabled(false);
			//Toast.makeText(CallRequestActivity.this, "Call 요청을 승낙하였습니다.", Toast.LENGTH_LONG).show();
			try {
				Thread.sleep(1500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			finish();
		}
		
		super.onNewIntent(intent);
	}

	
	// ===========================================================
	// Methods
	// ===========================================================
	// TODO: 콜 요청 전문 보내기
	// 1. 선택된 목적지 정보를 보내야 한다.
	// 2. 고객 정보를 보내야 한다.
	// 3. 인터페이스 문서보고 메소드 명/전문명 수정할 것.
	private void requestCall() {
		showProgressDialog(this, R.string.loading);
		
		DeviceUtil device = new DeviceUtil(this);
		
		String userPhoneNumber = device.getMDN();
		String addrNPsgNum = destinationSpinner.getSelectedItem().toString();
		// Log.e("HONG", "userPhoneNumber : " +userPhoneNumber );
		String[] addrNPsgNumArr = addrNPsgNum.split(":");
		String psgAddr1 = addrNPsgNumArr[0].trim();
		int psgNum = Integer.parseInt(addrNPsgNumArr[1].trim().substring(0, addrNPsgNumArr[1].length() - 2));
		
		gateway.call(driverPhoneNumber, userPhoneNumber, psgAddr1, psgNum, userLatitude, userLongitude,
				new CallListener() {

					@Override
					public void onNoNetwork() {
						dismissProgressDialog();
						Dialogs.showDialog(CallRequestActivity.this, getString(R.string.no_network), dialogListener);
					}

					@Override
					public void onNoResponse() {
						dismissProgressDialog();
						Dialogs.showDialog(CallRequestActivity.this, getString(R.string.no_respond), dialogListener);
					}

					@Override
					public void onSessionTimeOut() {
						dismissProgressDialog();
						Dialogs.showDialog(CallRequestActivity.this, getString(R.string.session_timeout),
								dialogListener);
					}

					@Override
					public void onSuccess(String acceptYn) {
						dismissProgressDialog();
						Toast.makeText(CallRequestActivity.this, getString(R.string.call_success), Toast.LENGTH_LONG)
								.show();
						if (acceptYn.equals("Y")) {
						} else if (acceptYn.equals("N")) {
							// callSuccessButton.setVisibility(View.GONE);
							// callRequestButton.setText("요청");
							// callRequestButton.setClickable(true);
							// callRequestButton.setBackgroundColor(color.gray);
							// callCancelButton.setClickable(true);
							// callCancelButton.setBackgroundColor(color.gray);
							// destinationSpinner.setClickable(true);
						}
					}

					@Override
					public void onFail(int code, String msg) {
						dismissProgressDialog();
						Dialogs.showDialog(CallRequestActivity.this, getString(R.string.server_message) + msg,
								dialogListener);
					}
				});
	}
	// ===========================================================
	// Inner and Anonymous Classes
	// ===========================================================
	private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			message = intent.getExtras().getString(Variables.CALL_REQUEST_SUCCESS_MESSAGE);
			Log.i(TAG, message);
		}
	};
	private OnClickListener clickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (v.getId() == R.id.call_request_button) {
				Log.i(TAG, ">>>>>>>>>>>> callRequest_button");
				requestCall();
				callRequestButton.setText("요청중");
				callRequestButton.setClickable(false);
				callRequestButton.setBackgroundColor(color.deepgray);
				callCancelButton.setClickable(false);
				callCancelButton.setBackgroundColor(color.deepgray);
				destinationSpinner.setClickable(false);
				// destinationSpinner.setBackgroundColor(color.deepgray);
				handler.postDelayed(updateTimerThread, 0);
				TimeOverCD = 1;
			} else if (v.getId() == R.id.call_cancel_button) {
				Log.i(TAG, ">>>>>>>>>>>> callCancel_button");
				onBackPressed();
			}
			return;
		}
	};
	private DialogListener dialogListener = new DialogListener() {

		@Override
		public void onClickedOk() {
			Dialogs.dismiss();
		}

		@Override
		public void onClickedCancel() {
			Dialogs.dismiss();
		}
	};
	private Runnable updateTimerThread = new Runnable() {

		public void run() {
			if (updatedTime == 0){
				TimeOverCD = 2;
				finish();
				return;
			}
			updatedTime -= 1;
			int mins = updatedTime / 60;
			int secs = updatedTime % 60;
			if (secs < 10)
				callCancelButton.setText("" + mins + ":0" + secs);
			else
				callCancelButton.setText("" + mins + ":" + secs);
			handler.postDelayed(this, 1000);
		}
	};
	
	@Override
	public void onBackPressed(){
		
		if(TimeOverCD == 0){
			finish();
		}else if(TimeOverCD == 1){
			return;
		}else if(TimeOverCD == 2){
			finish();
		}

		
		
	}

	@Override
	public void onBackClicked() {
		// TODO Auto-generated method stub
		finish();
	}

	@Override
	public void onAddClicked() {
		// TODO Auto-generated method stub
		
	}
}
